/**
 * Copyright (c) 2023 - present All rights reserved.
 * <p>
 * Reprinted has been protected by the copyright laws.
 */

package cn.myxl.smart.devkit.commit.action;

import cn.myxl.smart.devkit.commit.submission.CommitDialog;
import cn.myxl.smart.devkit.commit.model.SettingState;
import cn.myxl.smart.devkit.commit.persistent.HelperSetting;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.vcs.CommitMessageI;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.ui.Refreshable;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author zhangyang
 * @date 2023-11-14 16:01
 */

@Slf4j
public class CommitMessageAction extends AnAction implements DumbAware {
	HelperSetting helperSetting;

	public CommitMessageAction() {
		helperSetting = ApplicationManager.getApplication().getService(HelperSetting.class);
	}

	@Override
	public void actionPerformed(@NotNull AnActionEvent actionEvent) {
		SettingState settingState = helperSetting.getSettingState();

		final CommitMessageI commitPanel = getCommitPanel(actionEvent);

		if (commitPanel == null) {
			return;
		}

		CommitDialog dialog = new CommitDialog(actionEvent.getProject(), settingState);

		dialog.show();

		if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
			commitPanel.setCommitMessage(dialog.getCommitMessage(settingState).toString());
		}
	}

	@Nullable
	private static CommitMessageI getCommitPanel(@Nullable AnActionEvent e) {
		if (e == null) {
			return null;
		}
		Refreshable data = Refreshable.PANEL_KEY.getData(e.getDataContext());

		if (data instanceof CommitMessageI) {
			return (CommitMessageI) data;
		}
		return VcsDataKeys.COMMIT_MESSAGE_CONTROL.getData(e.getDataContext());
	}
}
